package com.lottery.ruok.lottrey.chat.activity;

import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.chat.MyConversationFragment;
import com.lottery.ruok.lottrey.chat.base.BaseChatActivity;
import com.lottery.ruok.lottrey.chat.model.system.SystemMessage;
import com.lottery.ruok.lottrey.chat.view.ChatRoomLotteryView;
import com.lottery.ruok.lottrey.chat.view.ChatRoomTitleBar;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.eventbusObject.PrizePushInfo;
import com.lottery.ruok.lottrey.eventbusObject.RefrashManagerEvent;
import com.lottery.ruok.lottrey.eventbusObject.RefrashRoomEvent;
import com.lottery.ruok.lottrey.eventbusObject.RongConversationType;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.AndroidBug5497Workaround;
import com.lottery.ruok.lottrey.utils.RongYunUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import com.lottery.ruok.lottrey.utils.AndroidBug5497Workaround;
import java.util.Locale;

import butterknife.BindView;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.ChatRoomInfo;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import utils.StringUtils;

/**
 * 会话
 */
public class ConversationActivity extends BaseChatActivity {
    public static final String EXTRA_LOTTERY_CODE = "extra_lottery_cdoe";

    @BindView(R.id.view_chatroom_title)
    ChatRoomTitleBar viewChatroomTitle;
    @BindView(R.id.view_chatroom_lottery)
    ChatRoomLotteryView viewChatroomLottery;
    @BindView(R.id.tv_message_cure)
    TextView tvMessageCure;
    @BindView(R.id.ll_message_cure)
    LinearLayout llMessageCure;

    private String mTargetId;
    private Conversation.ConversationType mConversationType;
    private String title;
    private ChatRoomTitleBar.ChatRoomTitleModel chatRoomTitleModel;
    private String lotteryCode;
    private String privateChatName;
    private String privateChatId;

    Handler myHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    if (RongYunUtil.isMannage(privateChatId)){
                        tvMessageCure.setText("管理员"+privateChatName+"向你发起对话");
                    }else {
                        tvMessageCure.setText(privateChatName+"向你发起对话");
                    }

                    llMessageCure.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    createTitleBarData();
                    viewChatroomTitle.setData(chatRoomTitleModel);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        if (intent != null) {
            mTargetId = intent.getData().getQueryParameter("targetId");
            mConversationType = Conversation.ConversationType.valueOf(intent.getData()
                    .getLastPathSegment().toUpperCase(Locale.US));

            title = intent.getData().getQueryParameter("title");
            lotteryCode = intent.getStringExtra(EXTRA_LOTTERY_CODE);
        }
        /**
         * 初始化titlebar数据
         */
        createTitleBarData();
        RongIM.getInstance().setConversationClickListener(new MyConversationClickListener());
    }

    /**
     * 初始化titlebar数据
     */
    private void createTitleBarData() {
        chatRoomTitleModel = new ChatRoomTitleBar.ChatRoomTitleModel();
        chatRoomTitleModel.setTitle(StringUtils.isEmpty(title) ? mTargetId : title);
        chatRoomTitleModel.setRule(UserInfo.getChatroom_role());
        chatRoomTitleModel.setChatType(mConversationType);
        chatRoomTitleModel.setTargetId(mTargetId);
        chatRoomTitleModel.setChatUserNum(UserInfo.getRoomNumCount());
    }

    @Override
    protected void initView() {
        setContentView(R.layout.conversation);
        AndroidBug5497Workaround.assistActivity(this);


        viewChatroomTitle.setData(chatRoomTitleModel);
        viewChatroomLottery.setLotteryCode(lotteryCode);
        if (mConversationType == Conversation.ConversationType.PRIVATE) {
            viewChatroomLottery.setVisibility(View.GONE);
        } else {
            viewChatroomLottery.setVisibility(View.VISIBLE);
        }

        llMessageCure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llMessageCure.setVisibility(View.GONE);
                if (com.lottery.ruok.lottrey.utils.StringUtils.isNotEmpty(privateChatId)) {
                    RongIM.getInstance().startPrivateChat(ConversationActivity.this, privateChatId, privateChatName);
                }

            }
        });
    }

    @Override
    protected void load() {
        if (mConversationType.getName().equals("private")){
            //消息时间间隔
            EventBus.getDefault().post(new RongConversationType(1));

        }else if (mConversationType.getName().equals("chatroom")){
            EventBus.getDefault().post(new RongConversationType(2));
            //刷新管理者
            EventBus.getDefault().post(new RefrashManagerEvent());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        viewChatroomLottery.onActivityResult(requestCode, resultCode, data);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PrizePushInfo event) {
        if (event.getCode() != null) {
            if (event.getCode().equals(viewChatroomLottery.getLotteryCode())) {
                String prizeNum = event.getPrizeNum();
                if (!StringUtils.isEmpty(prizeNum)) {
                    viewChatroomLottery.setLotteryReuslt(prizeNum);
                }
            }
        }
    }

    /* @Subscribe(threadMode = ThreadMode.MAIN)
     public void onMessageCureEvent(ChatPrivatePushInfo event) {
         if (mConversationType == Conversation.ConversationType.CHATROOM) {
             viewChatroomTitle.setCure(event.getTargetId(), event.getTargetName());
         }
     }*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(LoginSuccess event) {
        finish();
    }

    @Override
    public void onBackPressed() {
        MyConversationFragment fragment = (MyConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);
        if (!fragment.onBackPressed()) {
            super.onBackPressed();
        }
    }

    public void getChatRoomInfo() {
        RongIMClient.getInstance().getChatRoomInfo(mTargetId, -1, null, new RongIMClient.ResultCallback<ChatRoomInfo>() {
            @Override
            public void onSuccess(ChatRoomInfo chatRoomInfo) {
                int totalMemberCount = chatRoomInfo.getTotalMemberCount();
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        llMessageCure.setVisibility(View.GONE);
        RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            @Override
            public boolean onReceived(Message message, int i) {

                if (mConversationType == Conversation.ConversationType.CHATROOM) {
                    if (message.getConversationType().getName().equals("private")) {
                        //聊天室中新的私聊消息提醒
                        io.rong.imlib.model.UserInfo sendUser = RongUserInfoManager.getInstance().getUserInfo(message.getSenderUserId());
                        privateChatName = sendUser.getName();
                        privateChatId = sendUser.getUserId();
                        android.os.Message nessage = new android.os.Message();
                        nessage.what = 1;
                        myHandler.sendMessage(nessage);
                    }
                    if (message.getObjectName().equals("RCD:SysMsg")) {
                    //管理员身份变换提醒

                        SystemMessage systemMessage = (SystemMessage) message.getContent();
                        String targetId = systemMessage.getTargetUserId();
                        int status = systemMessage.getStatus();

                        if (targetId.equals(UserInfo.getMyUserId())) {
                            if (status==1){
                                UserInfo.setChatroom_role(2);
                            }else if (status==2){
                                UserInfo.setChatroom_role(1);
                            }else {
                                UserInfo.setChatroom_role(1);
                            }

                            android.os.Message nessage = new android.os.Message();
                            nessage.what = 2;
                            myHandler.sendMessage(nessage);
                        }

                        //刷新管理者
                        EventBus.getDefault().post(new RefrashManagerEvent());
                    }

                }
                return false;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mConversationType==Conversation.ConversationType.CHATROOM){
            EventBus.getDefault().post(new RefrashRoomEvent());
        }
        EventBus.getDefault().unregister(this);
    }

}
